package xhhx.network;

import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

public class GoogleProtobufDecode extends MessageToMessageDecoder<ByteBuf> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        int msgId = msg.getUnsignedShort(0);
        byte[] protoBufBytes = new byte[msg.capacity() - 2];
        msg.getBytes(2, protoBufBytes, 0, protoBufBytes.length);

        MessageLite recTemplate = MsgType.GetReceiveTemplate(msgId);
        if (recTemplate == null) {
            System.err.println("msgId:" + msgId + " recTemplate not find");
            return;
        }

        MessageLite rec = recTemplate.newBuilderForType().mergeFrom(protoBufBytes).build();

        C2sMsg recMsg = new C2sMsg(msgId, rec);

        out.add(recMsg);
    }
}
